

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="深海火锅店">
  <meta name="keywords" content="">
  
    <meta name="description" content="MySQL变量MySQL变量一共分为两大类:系统变量和用户自定义变量系统变量,由系统提供，不是用户定义，属于服务器层面  会话变量，仅仅针对当前会话(连接)有效 全局变量，服务器每次启动将为所有的全局变量赋初始值，针对于所有的会话(连接)有效用户自定义变量，就是字面的意思，由用户自定义的变量 局部变量，仅仅在定义它的BEGIN END中有效 会话变量，针对于当前会话(连接)有效，与会话变量作用域相">
<meta property="og:type" content="article">
<meta property="og:title" content="DB20_存储过程-编程基础">
<meta property="og:url" content="http://example.com/2022/12/30/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB20&DB21&DB22/DB20_%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B-%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="MySQL变量MySQL变量一共分为两大类:系统变量和用户自定义变量系统变量,由系统提供，不是用户定义，属于服务器层面  会话变量，仅仅针对当前会话(连接)有效 全局变量，服务器每次启动将为所有的全局变量赋初始值，针对于所有的会话(连接)有效用户自定义变量，就是字面的意思，由用户自定义的变量 局部变量，仅仅在定义它的BEGIN END中有效 会话变量，针对于当前会话(连接)有效，与会话变量作用域相">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-12-30T01:00:00.000Z">
<meta property="article:modified_time" content="2023-01-20T11:55:00.000Z">
<meta property="article:author" content="深海火锅店">
<meta property="article:tag" content="大数据">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>DB20_存储过程-编程基础 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/background.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="DB20_存储过程-编程基础"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-12-30 09:00" pubdate>
          2022年12月30日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.5k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          38 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">DB20_存储过程-编程基础</h1>
            
            
              <div class="markdown-body">
                
                <h3 id="MySQL变量"><a href="#MySQL变量" class="headerlink" title="MySQL变量"></a>MySQL变量</h3><p>MySQL变量一共分为两大类:系统变量和用户自定义变量系统变量,由系统提供，不是用户定义，属于服务器层面</p>
<ul>
<li>会话变量，仅仅针对当前会话(连接)有效</li>
<li>全局变量，服务器每次启动将为所有的全局变量赋初始值，针对于所有的会话(连接)有效用户自定义变量，就是字面的意思，由用户自定义的变量</li>
<li>局部变量，仅仅在定义它的BEGIN END中有效</li>
<li>会话变量，针对于当前会话(连接)有效，与会话变量作用域相同</li>
</ul>
<h3 id="查看系统变量"><a href="#查看系统变量" class="headerlink" title="查看系统变量"></a>查看系统变量</h3><p>系统变量分为全局级(GLOBAL)和会话级(SESSION)，故在客户端连接到服务端后，可以分别查看全局级的系统变量和当前连接会话的会话级系统变量</p>
<h3 id="修改系统变量"><a href="#修改系统变量" class="headerlink" title="修改系统变量"></a>修改系统变量</h3><p>系统变量分为全局级(GLOBAL)和会话级(SESSION)，所以，修改系统变量，也同样分为两种情形:修改会话级系统变量、修改全局级系统变量。修改系统全局变量需要SESSION_VARIABLES_ADMIN权限，一般由DBA用户进行。</p>
<p><strong>查看会话级系统变量</strong><br>可通过下述命令，来修改会话级系统变量。其只对当前连接的客户端的当次连接会话生效，对其他客户端无效。同样地，当不显式指定为session时，将默认修改会话级系统变量<br>set session variable &#x3D;value;<br>set variable &#x3D; value;<br>set @@session.variable &#x3D; value;<br>set @@variable &#x3D; value;<br><strong>修改全局级系统变量</strong><br>可通过下述命令，来修改全局级系统变量。如前所述，全局级系统变量用于在客户端建立连接时来初始化该连接会话的会话级系统变量。所以在Client 1修改了全局级系统变量后，该客户端的当次会话级系统变量的值不会发生更新。而只有其后续的新客户端连接时，才会应用修改后的全局级系统变量来初始化新连接的会话级系统变量<br>set global variable &#x3D; value;<br>set @@global.variable &#x3D; value;</p>
<h3 id="用户自定义会话变量"><a href="#用户自定义会话变量" class="headerlink" title="用户自定义会话变量"></a>用户自定义会话变量</h3><p>会话变量即为服务器为每个客户端连接维护的变量。在客户端连接时，使用相应全局变量的当前值对客户端的回话变量进行初始化。设置会话变量不需要特殊权限，但客户端只能更改自己的会话变量。其作用域与生命周期均限于当前客户端连接。</p>
<p><strong>会话变量的赋值</strong><br>set @variable_name &#x3D; expr;<br>set @variable_name :&#x3D; expr;<br><strong>会话变量的查询</strong><br>SELECT @variable_name;<br><strong>注意</strong>：变量名不区分大小写，即大小写不敏感</p>
<h3 id="用户自定义局部变量"><a href="#用户自定义局部变量" class="headerlink" title="用户自定义局部变量"></a>用户自定义局部变量</h3><p>作用范围在BEGIN到END语句块之间。在该语句块里设置的变量，DECLARE语句专门用于定义局部变量</p>
<ul>
<li>局部变量是使用DECLARE关键字声明</li>
<li>局部变量DECLARE语句出现的位置一定是在BEGIN和END之间，BEGIN..END是在函数&#x2F;存储过程&#x2F;触发器中使</li>
</ul>
<p>声明语法<br>DECLARE变量名数据类型[属性];<br>例如</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">DECLARE</span> RES <span class="hljs-type">INT</span> <span class="hljs-keyword">DEFAULT</span> O;<br></code></pre></td></tr></table></figure>
<p>赋值语法</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SET</span> 变量名<span class="hljs-operator">=</span>值;<br><span class="hljs-keyword">SET</span> 变量名:<span class="hljs-operator">=</span>值;<br></code></pre></td></tr></table></figure>
<p>例:</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">CREATE</span> PRDCEDURE example spl(<br>    <span class="hljs-keyword">IN</span> v1 <span class="hljs-type">INT</span>,<br>    <span class="hljs-keyword">IN</span> v2 <span class="hljs-type">INT</span>,<br>    <span class="hljs-keyword">OUT</span> ret1 <span class="hljs-type">INT</span>,<br>    <span class="hljs-keyword">OUT</span> ret2INT)<br><span class="hljs-keyword">BEGIN</span><br>    <span class="hljs-keyword">DECLARE</span> res,<span class="hljs-type">INT</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-number">0</span><br>    <span class="hljs-keyword">SET</span> res <span class="hljs-operator">=</span> v1<span class="hljs-operator">+</span>V2;<br>    <span class="hljs-keyword">SELECT</span> res <span class="hljs-keyword">INTO</span> ret1;<br>    <span class="hljs-keyword">SET</span> res :<span class="hljs-operator">=</span> v1<span class="hljs-operator">*</span>v2<br>    <span class="hljs-keyword">SELECT</span> res <span class="hljs-keyword">INTO</span> ret2;<br><span class="hljs-keyword">END</span>;<br></code></pre></td></tr></table></figure>

<h3 id="用户自定义变量详解"><a href="#用户自定义变量详解" class="headerlink" title="用户自定义变量详解"></a>用户自定义变量详解</h3><ul>
<li>可以利用SQL语句将值存储在用户自定义变量中，然后再利用另一条SQL语句来查询用户自定义变量。这样以来，可以再不同的SQL间传递值</li>
<li>用户自定义变量的声明方法形如:@variable_name，其中变量名称由字母、数字、””、”_”和”$”组成。当然，在以字符串或者标识符引用时也可以包含其他字符（例如:@’my-variable’，@”my-var”，或者@’my-var’)</li>
<li>用户自定义变量是会话级别的变量。其变量的作用域仅限于声明其的客户端链接。当这个客户端断开时，其所有的会话变量将会被释放</li>
<li>用户自定义变量是不区分大小写的</li>
<li>在使用SET设置变量时，可以使用&#x3D;或者:&#x3D;操作符进行赋值，在SELECT子句中赋值操作符只能使用:&#x3D;。因为&#x3D;操作符将会被认为是比较操作符</li>
<li>用户变量的类型仅限于整形、浮点型、二进制与非二进制串和NULL</li>
<li>如果用户自定义变量的值以结果集形式返回，系统会将其转换成字符串形式</li>
<li>如果查询一个没有初始化的变量，将会以字符串类型返回NULL。</li>
</ul>
<p><strong>变量的值是在SQL发送到客户端后才计算的</strong><br>在SELECT语句中，在每一个SELECT的变量表达式被发送给客户端后，才会进行计算。这就意味着，在形如HAVING，GROUP BY和ORDER BY子句是在服务器端执行)当其中有使用在当前SELECT表达式定义的变量的情况下，该语句将不会得到如期的效果。</p>
<p>在HAVING只句中使用了在当前的SELECT列表中定义的别名c2，其使用了变量@v1。这条语句并不会得到如期的效果:@v1变量为上一次SQL语句执行的结果集中的quantity值，并非当前的。</p>
<p>查询客户表的数据，按照客户名称生序排列，每行记录生成序号</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> (<span class="hljs-variable">@rnk</span> :<span class="hljs-operator">=</span> <span class="hljs-variable">@rnk</span> <span class="hljs-operator">+</span> <span class="hljs-number">1</span>)<span class="hljs-keyword">AS</span> rnk,t1.<span class="hljs-operator">*</span><br><span class="hljs-keyword">FROM</span> (<span class="hljs-keyword">SELECT</span> cust_id, cust_name<br>    <span class="hljs-keyword">FROM</span> example.customersORDER <span class="hljs-keyword">BY</span> cust_name) <span class="hljs-keyword">AS</span> t1<br><span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> (<span class="hljs-keyword">SELECT</span> <span class="hljs-variable">@rnk</span> :<span class="hljs-operator">=</span> <span class="hljs-number">0</span>) <span class="hljs-keyword">AS</span> t2<br></code></pre></td></tr></table></figure>

<h3 id="if语句"><a href="#if语句" class="headerlink" title="if语句"></a>if语句</h3><p>IF语句用来进行条件判断，根据是否满足条件(可包含多个条件)，来执行不同的语句，是流程控制中最常用的判断语句。其语法的基本形式如下</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql">IF search_condition <span class="hljs-keyword">THEN</span> statement_list<br>[ELSEIF search_condition <span class="hljs-keyword">THEN</span> statement_list]J...<br>[<span class="hljs-keyword">ELSE</span> statement_list]<br><span class="hljs-keyword">END</span> IF<br></code></pre></td></tr></table></figure>
<p>其中，search_condition参数表示条件判断语句，如果返回值为TRUE，相应的SQL语句列表(statement list）被执行;如果返回值为FALSE，则ELSE子句的语句列表被执行。statement_list可以包括一个或多个语句。<br>例子</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql">IF age<span class="hljs-operator">&gt;</span><span class="hljs-number">20</span> <span class="hljs-keyword">THEN</span> <span class="hljs-keyword">SET</span> counter1<span class="hljs-operator">=</span>counter1<span class="hljs-operator">+</span><span class="hljs-number">1</span>;<br>ELSEIF age<span class="hljs-operator">=</span><span class="hljs-number">20</span> <span class="hljs-keyword">THEN</span> <span class="hljs-keyword">SET</span> counter2<span class="hljs-operator">=</span>counter2<span class="hljs-operator">+</span><span class="hljs-number">1</span>;<br><span class="hljs-keyword">ELSE</span> <span class="hljs-keyword">SET</span> counter3<span class="hljs-operator">=</span>counter3<span class="hljs-operator">+</span><span class="hljs-number">1</span>;<br><span class="hljs-keyword">END</span> IF;<br></code></pre></td></tr></table></figure>
<p>SQL代码根据age与20的大小关系来执行不同的SET语句。如果age值大于20,那么将counter1的值加1;如果age值等于20，那么将counter2的值加1;其他情况将counter3的值加1。IF语句都需要使用ENDIF来结束。</p>
<h3 id="case语句"><a href="#case语句" class="headerlink" title="case语句"></a>case语句</h3><p>CASE语句也是用来进行条件判断的，它提供了多个条件进行选择，可以实现比IF语句更复杂的条件判断。CASE语句的基本形式如下</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">CASE</span> case_value<br><span class="hljs-keyword">WHEN</span> when_value <span class="hljs-keyword">THEN</span> statement_list<br>[<span class="hljs-keyword">WHEN</span> <span class="hljs-keyword">when</span> <span class="hljs-keyword">value</span> <span class="hljs-keyword">THEN</span> statement_list]...<br>[<span class="hljs-keyword">ELSE</span> statement_list]<br><span class="hljs-keyword">END</span> <span class="hljs-keyword">CASE</span><br></code></pre></td></tr></table></figure>
<p>case_value参数表示条件判断的变量，决定了哪一个WHEN子句会被执行<br>when_value参数表示变量的取值，如果某个when_value表达式与case_value变量的值相同，则执行对应的THEN关键字后的statement_list中的语句;<br>statement_list参数表示 when_value值没有与case_value相同值时的执行语句。<br>CASE语句都要使用END CASE结束</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">CASE</span> age<br>    <span class="hljs-keyword">WHEN</span> <span class="hljs-number">20</span> <span class="hljs-keyword">THEN</span> <span class="hljs-keyword">SET</span> counter2<span class="hljs-operator">=</span>counter2<span class="hljs-operator">+</span><span class="hljs-number">1</span>;<br>    <span class="hljs-keyword">ELSE</span> <span class="hljs-keyword">SET</span> counter3<span class="hljs-operator">=</span>counter3<span class="hljs-operator">+</span><span class="hljs-number">1</span>;<br><span class="hljs-keyword">END</span> <span class="hljs-keyword">CASE</span>;<br></code></pre></td></tr></table></figure>
<p>注意这种方式只能进行单值判断，无法进行类似age &gt;20的判断然后进行相关处理</p>
<h3 id="loop语句"><a href="#loop语句" class="headerlink" title="loop语句"></a>loop语句</h3><p>LOOP语句可以使某些特定的语句重复执行。与IF和CASE语句相比，LOOP只实现了一个简单的循环，并不进行条件判断。LOOP语句本身没有停止循环的语句，必须使用LEAVE语句等才能停止循环，跳出循环过程。<br>LOOP语句的基本形式如下</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs sql">[begin_label:]LOOP<br>    statement_list<br><span class="hljs-keyword">END</span> LOOP [end_label]<br></code></pre></td></tr></table></figure>
<p>其中,begin label参数和end_label参数分别表示循环开始和结束的标志，这两个标志必须相同，而且都可以省略;statement_list参数表示需要循环执行的语句。<br>例子:</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs sql">add_num: LOOP<br>    <span class="hljs-keyword">SET</span> counter<span class="hljs-operator">=</span><span class="hljs-variable">@counter</span><span class="hljs-operator">+</span><span class="hljs-number">1</span>;<br><span class="hljs-keyword">END</span> LOOP add_num;<br></code></pre></td></tr></table></figure>
<p>该示例循环执行counter加1的操作。因为没有跳出循环的语句（没有使用LEAVE语句)，这个循环成了一个死循环。LOOP循环都以END LOOP结束</p>
<h3 id="leave语句"><a href="#leave语句" class="headerlink" title="leave语句"></a>leave语句</h3><p>LEAVE语句主要用于跳出循环控制。其语法形式如下:<br>LEAVE label;<br>其中，label参数表示循环的标志，LEAVE语句必须跟在循环标志前面。一般LEAVE配合LOOP进行使用，使用条件判断来控制是否终止循环。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs sql">add_num: LOOP<br>    <span class="hljs-keyword">SET</span> counter<span class="hljs-operator">=</span><span class="hljs-variable">@counter</span><span class="hljs-operator">+</span><span class="hljs-number">1</span>;<br>    IF counter <span class="hljs-operator">=</span> <span class="hljs-number">100</span> <span class="hljs-keyword">THEN</span><br>        LEAVE add_num;<br>    <span class="hljs-keyword">ELSE</span> IF <span class="hljs-built_in">MOD</span>(counter, <span class="hljs-number">3</span>)<span class="hljs-operator">=</span> <span class="hljs-number">0</span> <span class="hljs-keyword">THEN</span><br>        ITERATE add_num;<br>        <span class="hljs-keyword">SELECT</span> <span class="hljs-operator">*</span><br>        <span class="hljs-keyword">FROM</span> example.order_totals;<br>    <span class="hljs-keyword">END</span> IF;<br><span class="hljs-keyword">END</span> LOOP add_num;<br></code></pre></td></tr></table></figure>
<p><strong>LEAVE与ITERATE的区别</strong><br>LEAVE语句和ITERATE语句都用来跳出循环语句，但两者的功能是不一样的。LEAVE语句是跳出整个循环,然后执行循环后面的程序。而ITERATE语句是跳出本次循环，然后进入下一次循环。使用这两个语句时一定要区分清楚。</p>
<h3 id="while语句"><a href="#while语句" class="headerlink" title="while语句"></a>while语句</h3><p>WHILE语句也是有条件控制的循环语句。WHILE语句和REPEAT语句不同的是,WHILE语句是当满足条件时，执行循环内的语句，否则退出循环。WHILE语句的基本语法形式如下:</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql">[begin_label:] WHILE search_condition DO<br>    statement_list<br>    UNTIL search_condition<br><span class="hljs-keyword">END</span> WHILE [end_label]<br></code></pre></td></tr></table></figure>
<p>其中</p>
<ul>
<li>search_condition参数表示循环执行的条件，满足该条件时循环执行</li>
<li>statement_list参数表示循环的执行语句。</li>
<li>WHILE循环需要使用END WHILE来结束</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs sql">WHILE counter <span class="hljs-operator">&lt;</span> <span class="hljs-number">100</span> DO<br>    <span class="hljs-keyword">SET</span> counter<span class="hljs-operator">=</span><span class="hljs-variable">@counter</span><span class="hljs-operator">+</span><span class="hljs-number">1</span>;<br><span class="hljs-keyword">END</span> WHILE;<br></code></pre></td></tr></table></figure>
<p>循环执行counter 加1的操作，counter值小于100时执行循环。如果counter值等于100了，则跳出循环</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%A4%A7%E6%95%B0%E6%8D%AE/" class="category-chain-item">大数据</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/">#大数据</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>DB20_存储过程-编程基础</div>
      <div>http://example.com/2022/12/30/数据库/MySQL/大数据学习/DB20&amp;DB21&amp;DB22/DB20_存储过程-编程基础/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>深海火锅店</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年12月30日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/12/30/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB20&amp;DB21&amp;DB22/DB21_%E5%AD%98%E5%82%A8%E5%87%BD%E6%95%B0/" title="DB21_存储函数">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">DB21_存储函数</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/12/29/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB18&amp;DB19/DB19_%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B1/" title="DB19_存储过程1">
                        <span class="hidden-mobile">DB19_存储过程1</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/EmoryHuang/BlogBeautify@1.1/DynamicRibbon.min.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
